package flc.ast.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.cartoonutil.lib.BaseController;
import com.stark.cartoonutil.lib.CartoonsController;
import com.stark.cartoonutil.lib.StyleTransferController;
import com.stark.cartoonutil.lib.utils.ImgUtil;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityCaricatureBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import jp.co.cyberagent.android.gpuimage.filter.GPUImageToonFilter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class CaricatureActivity extends BaseAc<ActivityCaricatureBinding> {

    public static String imgUri;
    private CartoonsController cartoonsController;
    private StyleTransferController styleTransferController;
    private int defWidth = -1;
    private int defHeight = -1;
    private Bitmap bitmap;
    private Dialog myTipDialog;
    private int style = 1;

    @Override
    protected int onCreate() {
        return R.layout.activity_caricature;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivCaricatureBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivCaricatureSave.setOnClickListener(this);
        mDataBinding.ivType1.setOnClickListener(this);
        mDataBinding.ivType2.setOnClickListener(this);
        mDataBinding.ivType3.setOnClickListener(this);
        mDataBinding.seekbarLevel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                GPUImageToonFilter filter = (GPUImageToonFilter) mDataBinding.gpuImgView.getFilter();
                filter.setLineSize(calLineSize(progress));
                mDataBinding.gpuImgView.requestRender();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivType1://样式1
                clearSelection();
                mDataBinding.ivType1Sel.setVisibility(View.VISIBLE);
                mDataBinding.ivType1.setVisibility(View.INVISIBLE);
                mDataBinding.seekbarLevel.setVisibility(View.VISIBLE);
                style = 1;
                mDataBinding.glImgView.setVisibility(View.GONE);
                mDataBinding.gpuImgView.setVisibility(View.VISIBLE);
                break;
            case R.id.ivType2://样式2
                clearSelection();
                mDataBinding.ivType2Sel.setVisibility(View.VISIBLE);
                mDataBinding.ivType2.setVisibility(View.INVISIBLE);
                mDataBinding.seekbarLevel.setVisibility(View.GONE);
                style = 2;
                mDataBinding.glImgView.setVisibility(View.VISIBLE);
                mDataBinding.gpuImgView.setVisibility(View.GONE);
                showDialog(getString(R.string.convert_ing));
                mDataBinding.glImgView.setImageSrc(bitmap.copy(bitmap.getConfig(), bitmap.isMutable()), true);
                cartoonsController.applyCartoonsModel(new BaseController.IApplyModelCallback() {
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.convert_suc);
                    }
                });
                break;
            case R.id.ivType3://样式3
                clearSelection();
                mDataBinding.ivType3Sel.setVisibility(View.VISIBLE);
                mDataBinding.ivType3.setVisibility(View.INVISIBLE);
                mDataBinding.seekbarLevel.setVisibility(View.GONE);
                style = 3;
                mDataBinding.glImgView.setVisibility(View.VISIBLE);
                mDataBinding.gpuImgView.setVisibility(View.GONE);
                showDialog(getString(R.string.convert_ing));
                mDataBinding.glImgView.setImageSrc(bitmap.copy(bitmap.getConfig(), bitmap.isMutable()), true);
                styleTransferController.applyStyleByImgInStorage(Uri.parse(imgUri), new BaseController.IApplyModelCallback() {
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.convert_suc);
                    }
                });
                break;
            case R.id.ivCaricatureSave://保存
                if (style == 1) {
                    saveImg1();
                } else if (style == 2) {
                    saveImg2();
                } else if (style == 3) {
                    saveImg3();
                }
                break;
            //提示弹框
            case R.id.ivDialogTipSave://退出并保存
                if (style == 1) {
                    saveImg1();
                } else if (style == 2) {
                    saveImg2();
                } else if (style == 3) {
                    saveImg3();
                }
                myTipDialog.dismiss();
                break;
            case R.id.ivDialogTipExit://直接退出
                myTipDialog.dismiss();
                finish();
                break;
            case R.id.ivDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.gpuImgView.setImage(Uri.parse(imgUri));
        mDataBinding.gpuImgView.setFilter(new GPUImageToonFilter());
        //该控制器用于对图片进行动漫化处理
        cartoonsController = new CartoonsController(mContext, mDataBinding.glImgView);
        styleTransferController = new StyleTransferController(mContext, mDataBinding.glImgView);
        showDialog(getString(R.string.loading));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (defWidth < 0) {
                    defWidth = mDataBinding.glImgView.getWidth();
                    defHeight = mDataBinding.glImgView.getHeight();
                }
                bitmap = ImgUtil.Companion.getCompressedBitmapByUri(imgUri, defWidth, defHeight);
                ViewGroup.LayoutParams layoutParams = mDataBinding.glImgView.getLayoutParams();
                layoutParams.width = bitmap.getWidth();
                layoutParams.height = bitmap.getHeight();
                mDataBinding.glImgView.setLayoutParams(layoutParams);
                mDataBinding.glImgView.setImageSrc(bitmap.copy(bitmap.getConfig(), bitmap.isMutable()), true);
                mDataBinding.glImgView.setVisibility(View.GONE);
                mDataBinding.gpuImgView.setVisibility(View.VISIBLE);
                dismissDialog();
            }
        }, 500);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //这里要释放资源
        if (styleTransferController != null) {
            styleTransferController.release();
            styleTransferController = null;
        }
    }

    private float calLineSize(int progress) {
        float start = 0f;
        float end = 5.0f;
        float ret = (end - start) * progress / 100f + start;
        return ret;
    }

    private void saveImg1() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<Uri>() {
            @Override
            public void doBackground(ObservableEmitter<Uri> emitter) {
                Uri uri = null;
                try {
                    Bitmap bitmap = mDataBinding.gpuImgView.capture();
                    uri = FileP2pUtil.saveBitmap2Jpg(mContext, bitmap);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                emitter.onNext(uri);
            }

            @Override
            public void accept(Uri uri) {
                dismissDialog();
                if (uri != null) {
                    String resultFile = FileUtil.generateFilePath(Content.MyCaricatureRecord, ".png");
                    FileP2pUtil.copyToPrivate(uri, resultFile);
                    startActivity(HomeActivity.class);
                }
                ToastUtils.showShort(uri != null ? getString(R.string.save_to_album) : getString(R.string.save_failure));
            }
        });
    }

    private void saveImg2() {
        showDialog(getString(R.string.save_ing));
        float aspectRatio = mDataBinding.glImgView.getWidth() * 1f / mDataBinding.glImgView.getHeight();
        cartoonsController.save(aspectRatio, new BaseController.ISaveCallback() {
            @Override
            public void onResult(@Nullable Uri fileUri) {
                dismissDialog();
                if (fileUri != null) {
                    String resultFile = FileUtil.generateFilePath(Content.MyCaricatureRecord, ".png");
                    FileP2pUtil.copyToPrivate(fileUri, resultFile);
                    startActivity(HomeActivity.class);
                }
                ToastUtils.showShort(fileUri != null ? getString(R.string.save_to_album) : getString(R.string.save_failure));
            }
        });
    }

    private void saveImg3() {
        showDialog(getString(R.string.save_ing));
        float aspectRatio = mDataBinding.glImgView.getWidth() * 1f / mDataBinding.glImgView.getHeight();
        styleTransferController.save(aspectRatio, new BaseController.ISaveCallback() {
            @Override
            public void onResult(@Nullable Uri fileUri) {
                dismissDialog();
                if (fileUri != null) {
                    String resultFile = FileUtil.generateFilePath(Content.MyCaricatureRecord, ".png");
                    FileP2pUtil.copyToPrivate(fileUri, resultFile);
                    startActivity(HomeActivity.class);
                }
                ToastUtils.showShort(fileUri != null ? getString(R.string.save_to_album) : getString(R.string.save_failure));
            }
        });
    }

    private void clearSelection() {
        mDataBinding.ivType1Sel.setVisibility(View.INVISIBLE);
        mDataBinding.ivType1.setVisibility(View.VISIBLE);
        mDataBinding.ivType2Sel.setVisibility(View.INVISIBLE);
        mDataBinding.ivType2.setVisibility(View.VISIBLE);
        mDataBinding.ivType3Sel.setVisibility(View.INVISIBLE);
        mDataBinding.ivType3.setVisibility(View.VISIBLE);
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.TOP);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 200;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView save = inflate.findViewById(R.id.ivDialogTipSave);
        ImageView exit = inflate.findViewById(R.id.ivDialogTipExit);
        ImageView cancel = inflate.findViewById(R.id.ivDialogTipCancel);
        save.setOnClickListener(this);
        exit.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

}